import traceback

from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from datetime import datetime


class BasePage():
    def __init__(self,driver):
        self.driver = driver

    # 查找指定元素
    def __get_element(self,locator,doc):
        print("开始查找元素%s"%str(locator))
        try:
            start_time = datetime.now()
            self.wait(locator)
            sel = self.driver.find_element(*locator)
            end_time = datetime.now()
            time = (end_time - start_time).seconds
            print("元素%s定位成功,用时%s"%(str(locator),time))
            return ele
        except Exception as e:
            print("查找%s元素"%str(locator))
            traceback.print_exc()   #打印错误报告
            self.get_screenshoot_as_file(doc)

    # 输入操作
    def input_context(self,locator,value,doc):

        ele = self.__get_element(locator,doc)
        ele.send_keys(value)

    # 点击操作
    def click_element(self,locator,doc):
        ele = self.__get_element(locator,doc)
        ele.click()

    def get_screenshoot_as_file(self,doc):
        """
        截图并保存
        :param doc: 模块名称_页面名称_操作名称
        :return:
        """
        self.driver.get_screenshot_as_file('../test_results/images/'+doc+'.png')
    def switch_into_frame(self,locator,doc):
        """
        切入frame框架中
        :param locator:
        :param doc:
        :return:
        """
        frame = self.__get_element(locator,doc)
        self.driver.switch_to.frame(frame)

    def switch_outo_frame(self):
        """
        从当前frame中切出
        :return:
        """
        self.driver.switch_to.default_content()

    def get_element_attribute(self,locator,doc,attribute):
        """
        获取元素的指定属性值
        :param locator: 元素定位方式
        :param doc: 截图图片名称
        :param attribute: 属性名称
        :return:
        """
        ele = self.__get_element(locator,doc)
        value = ele.get_attribute(attribute)
        return value
    def get_element_text(self,locator,doc):
        """
        获取元素的文本值
        :param locator:元素定位的方式
        :param doc: 截图图片名称
        :return:
        """
        ele = self.__get_element(locator,doc)
        text = ele.text
        return text

    def wait(self,locator,timeout=10,poll=0.5):
        """
        显示等待
        :param locator: 等待元素的定位方式
        :param timeout: 等待最长时间
        :param poll: 轮询时间
        :return:
        """
        try:
            start_time = datetime.now()
            WebDriverWait(self.driver,timeout,poll_frequency=poll).until(EC.visibility_of_element_located(locator))



















